package com.wj.rpsm.admin.controller;

import com.wj.rpsm.admin.pojo.PageResult;
import com.wj.rpsm.admin.pojo.ResponsePojo;
import com.wj.rpsm.admin.pojo.user.LoginUser;
import com.wj.rpsm.admin.pojo.user.ResUser;
import com.wj.rpsm.admin.pojo.user.User;
import com.wj.rpsm.admin.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Random;

/**
 * @author WeiJin
 * @version 1.0
 */
@RestController
@Api(tags = "用户相关接口")
public class UserController {


    @Autowired
    private UserService userService;

    @PostMapping("/admin/login")
    @ApiOperation(value = "根据账号和密码进行登录操作，只需账号和密码。返回个人信息和token字符串",
            notes = "<span style='color:red'>模拟操作，密码为明文密码</span>",
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", type = "String", required = true),
            @ApiImplicitParam(name = "password", type = "String", required = true)
    })
    @ApiParam
    public ResponsePojo<ResUser> login(@ApiIgnore LoginUser user) {

        user.setUser_type((short) 1);
        ResUser result = userService.Login(user);
        if (Optional.ofNullable(result).isPresent()) {
            return ResponsePojo.success(result);
        } else {
            return ResponsePojo.fail(null, "验证失败");
        }
    }


    @GetMapping("/page/user")
    @ApiOperation(value = "返回用户分页数据")
    @ApiParam
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页数"
                    , defaultValue = "1", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页面行数"
                    , dataType = "Integer", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "condition", value = "姓名或身份证查询关键字", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "user_type", value = "用户类型（1.管理员2.物业3.业主）"
                    , dataType = "Integer", required = true),})

    public ResponsePojo<PageResult<User>> getPage(
            @RequestParam(defaultValue = "1") Integer current,
            String condition, @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = true) Integer user_type) {
        PageResult<User> users = userService.pageOfUser(current, size, condition, user_type);
        ResponsePojo<PageResult<User>> res = ResponsePojo.success(users);
        return res;
    }


    @PostMapping("/admin/byid")
    @ApiOperation(value = "根据id查找单个用户   ",
            notes = "<span style='color:red'>根据用户id查询用户信息</span>",
            response = User.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "int", value = "用户id", paramType = "query")
    })
    @ApiParam
    public ResponsePojo<User> queryById(@RequestParam(required = true) Integer id) {
        User u = userService.searchById(id);
        return ResponsePojo.success(u);
    }


    @PostMapping("/updateAvatar")
    @ApiOperation("上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "multipartFile", value = "上传的文件", dataType = "_file",
                    dataTypeClass = MultipartFile.class, required = true)
    })
    public ResponsePojo<Map<String, String>> updateAvatar(
            @RequestPart MultipartFile multipartFile,
            @RequestParam("id") Integer id, HttpServletRequest request) {


        //声明返回值
        Map<String, String> map = new HashMap<>();
        //获取文件名，不同浏览器可能获取完整路径
        String filename = multipartFile.getOriginalFilename();

        //处理文件路径，获取文件名
        filename = filename.split("\\\\")[0];
        //String Path = app.getRealPath("/static/");//获取服务器文件夹的完整路径
        //由于这里没有运行真正的tomcat，无法获取正式地址，直接使用打包后的路径
        String path = "D:\\develop\\idea_workspace\\rpsm\\target\\classes\\static\\";
        //获取文件后缀名
        String sufName = filename.substring(filename.lastIndexOf('.') + 1);

        //判断后缀名
        if (!("png".equals(sufName) || "svg".equals(sufName)
                || "gif".equals(sufName) || "jpg".equals(sufName))) {
            map.put("message", "不是图片文件");
            return ResponsePojo.fail(map, "后缀名不是常见图片格式");
        }
        //文件大小判断
        if (multipartFile.getSize() >   1024 * 50) {//单位字节
            map.put("message", "文件体积太大");
            return ResponsePojo.fail(map, "文件超过50KB");
        }

        //确保唯一性，将文件保存时重命名
        filename = filename.length() > 3 ? filename.substring(0, 3) : filename;
        filename = filename + System.currentTimeMillis() + new Random().nextInt(1000) + "." + sufName;

        //保存到指定路径
        try {
            multipartFile.transferTo(new File(path + "img" + File.separator, filename));
        } catch (IOException e) {
            e.printStackTrace();
            map.put("message", "IO异常");
            return ResponsePojo.fail(map, e.getMessage());
        }

        //把文件路径保存到数据库
        User user = new User();
        user.setUserid(id);
        user.setUser_avatar(filename);
        userService.updateAvatar(user);
        map.put("message", "保存成功");
        return ResponsePojo.success(map);
    }


}
